Expand description
Metrics handling library based on the prometheus-client
crate.
§Overview
- The crate supports defining common metric types (
Counter
s,Gauge
s andHistogram
s). A single metric is represented by an instance of these types; it can be reported using methods likeCounter::inc()
,Gauge::set()
orHistogram::observe()
. - Metrics can be grouped into a
Family
. Essentially, aFamily
is a map in which metrics are values keyed by a set of labels. SeeEncodeLabelValue
andEncodeLabelSet
derive macros for more info on labels. - To define metrics, a group of logically related metrics is grouped into a struct
and the
Metrics
trait is derived for it. This resolves full metric names and records additional metadata, such as help (from doc comments), unit of measurement andBuckets
for histograms. - Metric groups are registered in a
Registry
, which then allows to encode metric data in the OpenMetrics text format. Registration can be automated using theregister
attribute, but it can be manual as well. - In order to allow for metrics computed during scraping, you can use
Collector
.
§Examples
§Defining metrics
use vise::*;
use std::{fmt, time::Duration};
/// Metrics defined by the library or application. A single app / lib can define
/// multiple metric structs.
#[derive(Debug, Clone, Metrics)]
#[metrics(prefix = "my_app")]
// ^ Prefix added to all field names to get the final metric name (e.g., `my_app_latencies`).
pub(crate) struct MyMetrics {
/// Simple counter. Doc comments for the fields will be reported
/// as Prometheus metric descriptions.
pub counter: Counter,
/// Integer-valued gauge. Unit will be reported to Prometheus and will influence metric name
/// by adding the corresponding suffix to it (in this case, `_bytes`).
#[metrics(unit = Unit::Bytes)]
pub gauge: Gauge<u64>,
/// Group of histograms with the "method" label (see the definition below).
/// Each `Histogram` or `Family` of `Histogram`s must define buckets; in this case,
/// we use default buckets for latencies.
#[metrics(buckets = Buckets::LATENCIES)]
pub latencies: Family<Method, Histogram<Duration>>,
}
/// Isolated metric label. Note the `label` name specification below.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, EncodeLabelSet, EncodeLabelValue)]
#[metrics(label = "method")]
pub(crate) struct Method(pub &'static str);
// For the isolated metric label to work, you should implement `Display` for it:
impl fmt::Display for Method {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}", self.0)
}
}
§Registering metrics automatically
Commonly, metrics can be registered by defining a static
:
#[derive(Debug, Clone, Metrics)]
pub(crate) struct MyMetrics {
// defined in a previous code sample
}
#[vise::register]
pub(crate) static MY_METRICS: Global<MyMetrics> = Global::new();
// All registered metrics can be collected in a `Registry`:
let registry: Registry = MetricsCollection::default().collect();
// Do something with the `registry`, e.g. create an exporter.
fn metered_logic() {
// method logic...
MY_METRICS.gauge.set(42);
}
§Registering metrics manually
It is possible to add metrics manually to a Registry
. As a downside, this approach requires
boilerplate to register all necessary metrics in an app and potentially libraries
that it depends on.
#[derive(Debug, Clone, Metrics)]
pub(crate) struct MyMetrics {
// defined in a previous code sample
}
let mut registry = Registry::empty();
let my_metrics = MyMetrics::default();
registry.register_metrics(&my_metrics);
// Do something with the `registry`, e.g. create an exporter.
// After registration, metrics can be moved to logic that reports the metrics.
// Note that metric types trivially implement `Clone` to allow sharing
// them among multiple components.
fn metered_logic(metrics: MyMetrics) {
// method logic...
metrics.gauge.set(42);
}
metered_logic(my_metrics);
Re-exports§
pub use crate::registry::METRICS_REGISTRATIONS;
pub use crate::registry::METRICS_REGISTRATIONS;
pub use crate::wrappers::LabelWithUnit;
Modules§
- Metric descriptors.
- Traits used for metric definitions, such as
GaugeValue
andHistogramValue
.
Structs§
- Error that can occur when calling
Collector::before_scrape()
. - Collector allowing to define metrics dynamically.
- Open Metrics
Counter
to measure discrete events. - Wraps a
Duration
so that it can be used as a label value, which will be set to the fractional number of seconds in the duration, i.e.Duration::as_secs_f64()
. Mostly useful forInfo
metrics. - Family of metrics labelled by one or more labels.
- Gauge metric.
- Guard for a
Gauge
returned byGauge::inc_guard()
. When dropped, a guard decrements the gauge by the same value that it was increased by when creating the guard. - Global instance of
Metrics
allowing to access contained metrics from anywhere in code. Should be used as astatic
item. - Histogram metric.
- Information metric.
- Observer of latency for a
Histogram
. - Configures collection of
register
ed metrics. - Visitor for a group of metrics in a
Registry
. - Descriptors of all metrics in a registry.
- Metrics registry.
- Error returned from
Info::set()
.
Enums§
- Metrics export format.
- Metric units recommended by Open Metrics.
Traits§
- Metric that can be constructed from a
MetricBuilder
. - Collection of metrics for a library or application. Should be derived using the corresponding macro.
Type Aliases§
Family
with separately specified label names.
Attribute Macros§
- Registers a
Global
metrics instance orCollector
, so that it will be included into registries instantiated usingMetricsCollection
.
Derive Macros§
- Derives the
EncodeLabelSet
trait for a type, which encodes a set of metric labels. - Derives the
EncodeLabelValue
trait for a type, which encodes a metric label value. - Derives the
Metrics
trait for a type.